package cn.com.tbshuda.mysql.mysql.packet;


import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

/**
 * @description: pdf相关的工具类
 */
@Component
public class PdfUtils {

    /**
     * 图片转换PDF的公共接口
     *
     * @param files    SpringMVC获取的图片文件
     * @param response HttpServletResponse
     * @throws IOException       IO异常
     * @throws DocumentException PDF文档异常
     */
    public static void imagesToPdf(MultipartFile[] files, HttpServletResponse response, String priUrl) throws IOException, DocumentException {
        ;
//        try {
//            fileItem.write(pdfFile);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        downloadPdfFile(generatePdfFiles(files, priUrl), response);
    }

    /**
     * 将图片转换为PDF文件
     *
     * @param files SpringMVC获取的图片文件
     * @return PDF文件
     * @throws IOException       IO异常
     * @throws DocumentException PDF文档异常
     */
    private static File generatePdfFiles(MultipartFile[] files, String priUrl) throws IOException, DocumentException {
        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
        String pdfFileName = priUrl + UUID.randomUUID().toString() + ".pdf";
        PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName));
        doc.open();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            doc.newPage();
            Image image = Image.getInstance(file.getBytes());
            float height = image.getHeight();
            float width = image.getWidth();
            int percent = getPercent(height, width);
            image.setAlignment(Image.MIDDLE);
            image.scalePercent(percent);
            doc.add(image);
        }
        doc.close();
        File pdfFile = new File(pdfFileName);
        return pdfFile;
    }

    /**
     * 图片转换PDF的公共接口
     *
     * @param file     SpringMVC获取的图片文件
     * @param response HttpServletResponse
     * @throws IOException       IO异常
     * @throws DocumentException PDF文档异常
     */
    public static void imageToPdf(MultipartFile file, HttpServletResponse response) throws IOException, DocumentException {
        File pdfFile = generatePdfFile(file);
        downloadPdfFile(pdfFile, response);
    }

    /**
     * 将图片转换为PDF文件
     *
     * @param file SpringMVC获取的图片文件
     * @return PDF文件
     * @throws IOException       IO异常
     * @throws DocumentException PDF文档异常
     */
    private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException {
        String fileName = file.getOriginalFilename();
        String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
        PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName));
        doc.open();
        doc.newPage();
        Image image = Image.getInstance(file.getBytes());
        float height = image.getHeight();
        float width = image.getWidth();
        int percent = getPercent(height, width);
        image.setAlignment(Image.MIDDLE);
        image.scalePercent(percent);
        doc.add(image);
        doc.close();
        File pdfFile = new File(pdfFileName);
        return pdfFile;
    }

    /**
     * 用于下载PDF文件
     *
     * @param pdfFile  PDF文件
     * @param response HttpServletResponse
     * @throws IOException IO异常
     */
    private static void downloadPdfFile(File pdfFile, HttpServletResponse response) throws IOException {
        InputStream inStream = new FileInputStream(pdfFile);
        byte[] bytes = new byte[inStream.available()];
        System.out.println("文件大小==" + bytes.length);

        response.setHeader("Content-Type", "application/pdf");
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(pdfFile.getName(), "UTF-8"));
//        ServletOutputStream out = response.getOutputStream();
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//        downloadFile(fis, out);
//        HttpURLConnection connection = null;
//        ServletOutputStream out = response.getOutputStream();
//        if (pdfFile!= null) {
//            String url = null;
////            for (Map.Entry<String, String> entry : fileMap.entrySet()) {
////                url = entry.getValue();
////            }
//            try {
////                connection = getConnection(url);
//                downloadFile(fis, out);
//            } catch (Exception e) {
//               e.printStackTrace();
//            }
//            return;
//        }

    private static HttpURLConnection getConnection(String url) throws Exception {
        URL conUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) conUrl.openConnection();
        connection.connect();
        return connection;
    }

    /**
     * 下载指定输入流的图片
     *
     * @param is  输入流
     * @param out 输出流
     * @throws Exception 异常
     */
    private static void downloadFile(InputStream is, OutputStream out) throws Exception {
        try {
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                out.write(b, 0, length);
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (is != null) {
                is.close();
            }
        }
    }

    /**
     * 等比压缩，获取压缩百分比
     *
     * @param height 图片的高度
     * @param weight 图片的宽度
     * @return 压缩百分比
     */
    private static int getPercent(float height, float weight) {
        float percent = 0.0F;
        if (height > weight) {
            percent = PageSize.A4.getHeight() / height * 100;
        } else {
            percent = PageSize.A4.getWidth() / weight * 100;
        }
        return Math.round(percent);
    }
}
